#deploy document management site
function WaitForJobToFinish([string]$SolutionFileName)
{ 
    $JobName = "*solution-deployment*$SolutionFileName*"
    $job = Get-SPTimerJob | ?{ $_.Name -like $JobName }
    if ($job -eq $null) 
    {
        Write-Host 'Timer job not found'
    }
    else
    {
        $JobFullName = $job.Name
        Write-Host -NoNewLine "Waiting to finish job $JobFullName"

        while ((Get-SPTimerJob $JobFullName) -ne $null) 
        {
            Write-Host -NoNewLine .
            Start-Sleep -Seconds 2
        }
		Write-Host
        Write-Host  "Finished waiting for job.."
    }
}


function Update-Scopes($siteUrl)
{
	[void][reflection.assembly]::Loadwithpartialname("Microsoft.SharePoint") | out-null
	[void][reflection.assembly]::Loadwithpartialname("Microsoft.office.server.search") | out-null
	
	$s = [microsoft.sharepoint.spsite]$siteUrl
	$sc = [microsoft.office.server.servercontext]::GetContext($s)
	$search = [Microsoft.Office.Server.Search.Administration.SearchContext]::GetContext($sc)
	$scopes = [microsoft.office.server.search.administration.scopes]$search
	$scopes.StartCompilation()
	while ($scopes.CompilationPercentComplete -lt 100) { sleep -seconds 3; write-host "$($scopes.CompilationPercentComplete)% complete" }
}


#Load variables from configuration file
[System.Xml.XmlDocument] $xmlDoc = New-Object System.Xml.XmlDocument
$file = Resolve-Path (".\deployment.config")

if(!$file){
	Write-Host "Could not find the configuration file deployment.cnofig. Aborting." -ForegroundColor Red
	break
}

Write-Host "Parsing file: " $file
$xmlDoc = [xml](Get-Content $file)

$webAppUrl = $xmlDoc.Configuration.WebApplication.Url
$siteCollectionUrl = $xmlDoc.Configuration.WebApplication.SiteCollection.Url
$siteName =$xmlDoc.Configuration.WebApplication.SiteCollection.SiteName
$siteTemplateId = $xmlDoc.Configuration.WebApplication.SiteCollection.SiteTemplateId
$primaryAdminAccount = $xmlDoc.Configuration.WebApplication.SiteCollection.PrimaryAdminAccount

$wspPackagePath = $xmlDoc.Configuration.WSPPackage.PackagePath
$wspPackageName = $xmlDoc.Configuration.WSPPackage.Name
$docsBoxWspPackagePath = $xmlDoc.Configuration.DocsBoxPackage.PackagePath
$docsBoxwspPackageName = $xmlDoc.Configuration.DocsBoxPackage.Name


$searchService = $xmlDoc.Configuration.SearchService.Name
$scopeName =$xmlDoc.Configuration.SearchService.SearchScope.Name

$invoiceRootSiteUrl = $xmlDoc.Configuration.WebApplication.SiteCollection.InvoiceSite.Url
$receiptRootSiteUrl = $xmlDoc.Configuration.WebApplication.SiteCollection.ReceiptSite.Url
$gatsRootSiteUrl = $xmlDoc.Configuration.WebApplication.SiteCollection.GATSSite.Url
$caRootSiteUrl = $xmlDoc.Configuration.WebApplication.SiteCollection.CASite.Url
$searchRootSiteUrl = $xmlDoc.Configuration.WebApplication.SiteCollection.SearchSite.Url
$docsBoxRootSiteUrl = $xmlDoc.Configuration.WebApplication.SiteCollection.DocsBoxSite.Url



$invoiceScopeName = $xmlDoc.Configuration.SearchService.InvoiceSearchScope.Name
$receiptScopeName = $xmlDoc.Configuration.SearchService.ReceiptSearchScope.Name

#@@@@@@@@@@@@@@@@@@@@@@@variables can't be change from this point@@@@@@@@@@@@@@@@@@@@
#activate feature
$recreateSiteCollection = $true


$dmsBrandingFeatureId="28509740-6361-4d6f-b34d-dad9f4804277"
$listProvisioningFeatureId="dd04962e-73b4-4021-83bf-95129703e6f0"
$documentStoreFeatureId="62bf7719-32c1-41f8-8ad8-b94c4887c63b"
$searchProvisionFeatureId="341b093a-f997-4454-b887-3105a9919945"


$invoiceHomepageFeatureId = "eedea87f-e153-41e7-b386-3bd766d8703a"
$caHomepageFeatureId = "e44372bb-c758-497f-ae04-9342e1ee035c"
$gatHomepageFeatureId = "dc553a03-b207-4303-8758-e95d2e25ab1c"
$receiptHomepageFeatureId = "bc71a813-c5c8-4cf2-bd7b-0e49c2acfd71"
$docsBoxFeatureId = "efa1833d-f33b-41aa-9029-a8f7246ad817"


#@@@@@@@@@@@@ No Change Required From THIS LINE @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue
Write-Host "*****CHECK PDF ENABLED IN BROWSER*****" -ForegroundColor Yellow
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")


$wspID = Get-SPSolution -Identity $wspPackageName -ErrorAction SilentlyContinue 

if($wspID.Status -eq $null){
	Write-Host "The WSP solution did not deployed"
}else{

Write-Host "*****REMOVE SOLUTION" $wspPackageName "*****" -ForegroundColor Yellow
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
#uninstall and remove solution before delete site collection
Write-Host "Retracting Solution ..."
Uninstall-SPSolution -identity $wspPackageName -WebApplication $WebAppUrl -Confirm:$false

WaitForJobToFinish


Write-Host "Removing Solution ..."

Remove-SPSolution -identity $wspPackageName -Confirm:$false

}


#remove and install Docsbox solution

$docsBoxWspID = Get-SPSolution -Identity $docsBoxwspPackageName -ErrorAction SilentlyContinue 

if($docsBoxWspID.Status -eq $null){
	Write-Host "The Docsbox WSP solution did not deployed"
}else{

Write-Host "*****REMOVE SOLUTION" $docsBoxwspPackageName "*****" -ForegroundColor Yellow
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
#uninstall and remove solution before delete site collection
Write-Host "Retracting Solution ..."
Uninstall-SPSolution -identity $docsBoxwspPackageName -WebApplication $WebAppUrl -Confirm:$false

WaitForJobToFinish


Write-Host "Removing Solution ..."

Remove-SPSolution -identity $docsBoxwspPackageName -Confirm:$false

}

Write-Host "*****Re-Create Site Collection " $siteCollectionUrl "*****" -ForegroundColor Yellow
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

if($recreateSiteCollection){
	.\SharePoint2010-RecreateSiteCollection.ps1 -siteCollectionUrl $siteCollectionUrl -siteName $siteName -siteTemplateId $siteTemplateId -primaryAdmin $primaryAdminAccount
}

Write-Host "RESTART IIS"
net stop w3svc
net start w3svc

Write-Host "*****ADD SOLUTION" $wspPackageName "*****" -ForegroundColor Yellow
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Write-Host "Adding Solution " $wspPackageName
stsadm -o addsolution -filename $wspPackagePath

Write-Host "Deploying Solution " $wspPackageName
stsadm -o deploysolution -name $wspPackageName -allowGacDeployment -immediate -url $webAppUrl
#Start-Sleep 20
WaitForJobToFinish
stsadm -o execadmsvcjobs
#Start-Sleep 20


Write-Host "*****ADD SOLUTION" $docsBoxwspPackageName "*****" -ForegroundColor Yellow
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Write-Host "Adding Solution " $docsBoxwspPackageName
stsadm -o addsolution -filename $docsBoxwspPackagePath

Write-Host "Deploying Solution " $docsBoxwspPackageName
stsadm -o deploysolution -name $docsBoxwspPackageName -allowGacDeployment -immediate -url $webAppUrl
#Start-Sleep 20
WaitForJobToFinish
stsadm -o execadmsvcjobs
#Start-Sleep 20





Write-Host "*****ACTIVATE FEATURES*****" -ForegroundColor Yellow
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Write-Host "Activating feature 1 DMSBranding..."
stsadm -o activatefeature -id $dmsBrandingFeatureId -url $siteCollectionUrl -force 
Start-Sleep 20
Write-Host "Activating feature 2 ListProvisioniing..."
stsadm -o activatefeature -id $listProvisioningFeatureId -url $siteCollectionUrl -force 
Start-Sleep 20
Write-Host "Activating feature 3 DocumentStore..."
stsadm -o activatefeature -id $documentStoreFeatureId -url $siteCollectionUrl -force 
Start-Sleep 5


Write-Host "Activating feature 4 SearchProvision..."
stsadm -o activatefeature -id $searchProvisionFeatureId -url $searchRootSiteUrl -force 
Start-Sleep 5

Write-Host "Activating feature 5 InvoiceHomePage..."
stsadm -o activatefeature -id $invoiceHomepageFeatureId -url $invoiceRootSiteUrl -force 
Start-Sleep 5

Write-Host "Activating feature 6 CreditApplicationHomepage..."
stsadm -o activatefeature -id $caHomepageFeatureId -url $caRootSiteUrl -force 
Start-Sleep 5

Write-Host "Activating feature 7 GATsHomepage..."
stsadm -o activatefeature -id $gatHomepageFeatureId -url $gatsRootSiteUrl -force 
Start-Sleep 5


Write-Host "Activating feature 8 ReceiptHomepage..."
stsadm -o activatefeature -id $receiptHomepageFeatureId -url $receiptRootSiteUrl -force 
Start-Sleep 5


Write-Host "Activating feature 8 ReceiptHomepage..."
stsadm -o activatefeature -id $docsBoxFeatureId -url $docsBoxRootSiteUrl -force 
Start-Sleep 5




Write-Host "*****CONFIGURE SEARCH SCOPES SETTING*****" -ForegroundColor Yellow

$caCrawlList = "$caRootSiteUrl/CreditApplications"
$gatsCrawlList = "$gatsRootSiteUrl/gats"


$ssa = Get-SPEnterpriseSearchServiceApplication -Identity $searchService
$scope = Get-SPEnterpriseSearchQueryScope -Identity $scopeName -SearchApplication $ssa -ErrorAction SilentlyContinue
#create search scope
if($scope -ne $null){
	$NumberOfRules = $scope.Rules.Count
	$cbDeleted = $scope.CanBeDeleted
	if($scope.CanBeDeleted -eq $TRUE){
		Remove-SPEnterpriseSearchQueryScope -Identity $scopeName -SearchApplication $ssa -Confirm:$false
		Write-Host "Creating Search Scope $scopeName" -ForegroundColor Yellow
		New-SPEnterpriseSearchQueryScope -Name $scopeName -Description "Search Scope for Document Management System" -DisplayInAdminUI $true -SearchApplication $ssa
	}else
	{
		Write-Host "Remove All Rules in Search Scope $scopeName" -ForegroundColor Yellow
		$NumberOfRules = $scope.Rules.Count
		if($NumberOfRules -gt 0){
			Write-Host "Login to Central Admin to remove all existing Search Scope Rules"
			while($NumberOfRules -gt 0){
				Write-Host -NoNewLine .
	            Start-Sleep -Seconds 2
				$scope = Get-SPEnterpriseSearchQueryScope -Identity $scopeName -SearchApplication $ssa -ErrorAction SilentlyContinue
				$NumberOfRules = $scope.Rules.Count
			}
			Write-Host
		}
	}
}else{
	New-SPEnterpriseSearchQueryScope -Name $scopeName -Description "Search Scope for Document Management System" -DisplayInAdminUI $true -SearchApplication $ssa
	
}


#add crawl rule to the search scope 
$scope = Get-SPEnterpriseSearchQueryScope -Identity $scopeName -SearchApplication $ssa
Write-Host "Creating Search Scope Rule $caCrawlList" -ForegroundColor Yellow
$sr = New-SPEnterpriseSearchQueryScopeRule -Scope $scope -RuleType Url -FilterBehavior Include -UrlScopeRuleType Folder -MatchingString $caCrawlList -Url $siteCollectionUrl
Write-Host "Creating Search Scope Rule $gatsCrawlList" -ForegroundColor Yellow
$sr = New-SPEnterpriseSearchQueryScopeRule -Scope $scope -RuleType Url -FilterBehavior Include -UrlScopeRuleType Folder -MatchingString $gatsCrawlList -Url $siteCollectionUrl



Write-Host "*****CREATE INVOICE SEARCH SCOPES *****" -ForegroundColor Yellow

$invoicescope = Get-SPEnterpriseSearchQueryScope -Identity $invoiceScopeName -SearchApplication $ssa -ErrorAction SilentlyContinue
if($invoicescope -ne $null){
		
	$NumberOfRules = $invoicescope.Rules.Count
	$cbDeleted = $invoicescope.CanBeDeleted
	
	if($invoicescope.CanBeDeleted -eq $TRUE){
		Write-Host "Removing Invoice Search Scope $invoiceScopeName" -ForegroundColor Yellow
		Remove-SPEnterpriseSearchQueryScope -Identity $invoiceScopeName -SearchApplication $ssa -Confirm:$false
		Write-Host "Creating Invoice Search Scope $invoiceScopeName" -ForegroundColor Yellow
		New-SPEnterpriseSearchQueryScope -Name $invoiceScopeName -Description "Search Scope for Invoices Documents" -DisplayInAdminUI $true -SearchApplication $ssa
	}else
	{
		Write-Host "Remove All Rules in Search Scope $invoiceScopeName" -ForegroundColor Yellow
		$NumberOfRules = $invoicescope.Rules.Count
		if($NumberOfRules -gt 0){
			Write-Host "Login to Central Admin to remove all existing Search Scope Rules"
			while($NumberOfRules -gt 0){
				Write-Host -NoNewLine .
	            Start-Sleep -Seconds 2
				$invoicescope = Get-SPEnterpriseSearchQueryScope -Identity $invoiceScopeName -SearchApplication $ssa -ErrorAction SilentlyContinue
				$NumberOfRules = $invoicescope.Rules.Count
			}
			Write-Host
		}
	}
}else{

	Write-Host "Creating Invoice Search Scope $invoiceScopeName" -ForegroundColor Yellow
	New-SPEnterpriseSearchQueryScope -Name $invoiceScopeName -Description "Search Scope for Invoice Documents" -DisplayInAdminUI $true -SearchApplication $ssa
}



Write-Host "*****CREATE RECEIPT SEARCH SCOPES *****" -ForegroundColor Yellow

$receiptscope = Get-SPEnterpriseSearchQueryScope -Identity $receiptScopeName -SearchApplication $ssa

if($receiptscope -ne $null){
		
	$NumberOfRules = $receiptscope.Rules.Count
	$cbDeleted = $receiptscope.CanBeDeleted
	
	if($receiptscope.CanBeDeleted -eq $TRUE){
		Write-Host "Removing Receipt Search Scope $receiptScopeName" -ForegroundColor Yellow
		Remove-SPEnterpriseSearchQueryScope -Identity $receiptScopeName -SearchApplication $ssa -Confirm:$false
		Write-Host "Creating Receipt Search Scope $receiptScopeName" -ForegroundColor Yellow
		New-SPEnterpriseSearchQueryScope -Name $receiptScopeName -Description "Search Scope for Receipt Documents" -DisplayInAdminUI $true -SearchApplication $ssa
	}else
	{
		Write-Host "Remove All Rules in Search Scope $receiptScopeName" -ForegroundColor Yellow
		$NumberOfRules = $receiptscope.Rules.Count
		if($NumberOfRules -gt 0){
			Write-Host "Login to Central Admin to remove all existing Search Scope Rules"
			while($NumberOfRules -gt 0){
				Write-Host -NoNewLine .
	            Start-Sleep -Seconds 2
				$receiptscope = Get-SPEnterpriseSearchQueryScope -Identity $receiptScopeName -SearchApplication $ssa -ErrorAction SilentlyContinue
				$NumberOfRules = $receiptscope.Rules.Count
			}
			Write-Host
		}
	}
}else{

	Write-Host "Creating Invoice Search Scope $invoiceScopeName" -ForegroundColor Yellow
	New-SPEnterpriseSearchQueryScope -Name $receiptScopeName -Description "Search Scope for Invoice Documents" -DisplayInAdminUI $true -SearchApplication $ssa
}

Update-Scopes -siteUrl $siteCollectionUrl

Write-Host "Deployment Completed." -ForegroundColor Green

Remove-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue


